﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Safal.IncidentTracker.WebUI.HtmlHelpers
{
    public class PagedList<T> : List<T>, IPagedList
    {
        public PagedList(IQueryable<T> source, int index, int pageSize)
        {
            this.TotalCount = source.Count();
            this.PageIndex = index;
            this.PageSize = pageSize;
            this.AddRange(source.Skip(index * pageSize).Take(pageSize));
        }

        
        public int TotalCount { get; set; }
        public int TotalPages { get { return (int)Math.Ceiling((decimal)TotalCount / PageSize); } }
        public int PageIndex { get; set; }
        public int PageSize { get; set; }

        public int CurrentPage { get { return PageIndex + 1; } }

        public int NextPage { get { return CurrentPage + 1; } }

        public int PreviousPage { get { return CurrentPage - 1; } }

        public bool HasPreviousPage { get { return CurrentPage > 1; } }

        public bool HasNextPage { get { return CurrentPage < TotalPages; } }
        
        public bool IsCurrentPage(int pageNumber)
        {
            return pageNumber == CurrentPage;
        }
    }

    public static class Pagination
    {
        public static PagedList<T> ToPagedList<T>(this IQueryable<T> source, int index, int pageSize)
        {
            return new PagedList<T>(source, index, pageSize);
        }

        public static PagedList<T> ToPagedList<T>(this IQueryable<T> source, int index)
        {
            return new PagedList<T>(source, index, 10);
        }
    }
}